﻿using UnityEngine;
using UnityEditor;
namespace BehaviorSystem
{
    /// <summary>
    /// 组合节点基类
    /// </summary>
    public class CompositeNode : BehaviourNode
    {
        
        protected int curIndex = 0;

        public CompositeNode(IBehaviorAgent agent) : base(agent)
        {
        }

        public override BTNodeState ExcuteNode()
        {
            OnExcuted();
            if (CurState == BTNodeState.Invalid )
            {
                return CurState;
            }
            if (CurState == BTNodeState.Success || CurState == BTNodeState.Failure)
            {
                OnReseted();
                ResetNode();
            }
            BTNodeState tempNodeState;

            if (IsNeedReDoPerTick)
            {
                for (int i = 0; i <= curIndex; i++)
                {
                    tempNodeState = ChildrenNodes[i].CurState;
                    if (ChildrenNodes[i].IsNeedReDoPerTick &&
                        (tempNodeState == BTNodeState.Failure) || tempNodeState == BTNodeState.Invalid)
                    {

                        BTNodeState reDoState = ChildrenNodes[i].ExcuteNode();
                        if (reDoState == BTNodeState.Success || reDoState == BTNodeState.Running)
                        {
                            curIndex = i;
                        }
                    }
                }
            }


            return HandleComposite();
        }

        public virtual BTNodeState HandleComposite()
        {
            return BTNodeState.Success;
        }

        public override void ResetNode()
        {
            OnReseted();
            CurState = BTNodeState.Running;
            curIndex = 0;
            for (int i = 0; i < ChildrenNodes.Count; i++)
            {
                ChildrenNodes[i].ResetNode();
            }
        }
    }
}